var confirmImg = '';

myApp.onPageInit('work-item-list', function (page) {
    console.log("onPageInit " + page.name);

    var list = $$(page.container).find('.list-block'),
        ul = list.find('ul'),
        empty = $$(page.container).find('.empty-view'),
        refreshContainer = $$(page.container).find('.pull-to-refresh-content');
    list.data('request', null);
    list.data('lastpage', false);
    list.data('nextpage', 0);

    function loadPage() {
        var refresing = list.data('nextpage') == 0,
            req = true;
        $$.getJSONP(SERVER_PATH + 'getWorkItemList.do', {num: PAGE_SIZE, start: (list.data('nextpage') * PAGE_SIZE)}, function (json) {
            if (json.code == 1) {
                list.data('nextpage', list.data('nextpage') + 1);

                if (refresing) {
                    ul.children().remove();
                }

                $$.each(json.results, function (index, value) {
                    if (value.isLastPage) {
                        list.data('lastpage', true);
                    }

                    preprocessData('workItemList', value);
                    var html = Template7.templates.workItemTemplate(value);
                    ul.append(html);
                });
                empty[ul.children().length > 0 ? 'hide' : 'show']();
            }

            list.data('request', null);
            if (refresing) {
                myApp.pullToRefreshDone(refreshContainer);
            }
        });
        list.data('request', req);
    }

    ul.on('click', 'a.item-link', function () {
        $$(this).find('.badge').hide();
    });

    $$(page.container).find('.infinite-scroll').on('infinite', function () {
        if (list.data('lastpage') || list.data('request')) {
            return;
        }

        loadPage();
    });
    refreshContainer.on('refresh', function (e) {
        var request = list.data('request');
        if (request) {
            request.abort();
        }
        list.data('request', null);
        list.data('lastpage', false);
        list.data('nextpage', 0);
        loadPage();
    });
    myApp.pullToRefreshTrigger(refreshContainer);
});

myApp.onPageBeforeInit('work-item-detail', function (page) {
    if (myApp.padApp) {
        $$(page.navbarInnerContainer).find('.left').css('visibility', 'hidden');
    }
});
myApp.onPageAfterAnimation('work-item-detail', function (page) {
    if (!localStorage.getItem('popover-menu-showed')) {
        localStorage.setItem('popover-menu-showed', true);
        myApp.popover('.popover-menu', $$(page.navbarInnerContainer).find('.right'));
    }
});

myApp.onPageAfterBack('work-item-detail', function (page) {
	$$('.page[data-page="work-item-list"] .pull-to-refresh-content').trigger('refresh');
});

myApp.onPageInit('work-item-detail', function (page) {
    console.log("onPageInit " + page.name);
    var params = page.query,
        workData;

    $$(page.container).find('.tab1').on('show', function () {
        $$(page.navbarInnerContainer).find('.center').text('处理单');
    });
    
    if(page.query.weboffice == "false"){      	
    	$$(page.navbarInnerContainer).find('.i-content').css("display","none");
    }
   
    $$(page.container).find('.tab2').on('show', function () {
        $$(page.navbarInnerContainer).find('.center').text('正文');
        var tab = $$(this),
            empty = tab.find('.empty-view');

        if (workData) {
            $$.getJSONP(SERVER_PATH + 'hasFileReleasePub.do', {
                formDefId: workData.hiddenValue.formDefId,
                businessId: workData.hiddenValue.businessId
            }, function (json) {
                if (json.code == 1) {
                    if (json.results.url) {
                        empty.hide();
                        myApp.showTab('#tab1');
                      /*	$(iframe[0]).load(function () {
							 var width = $(document).width();
                       	 var that = $(this);
                            $(this).height($(document).height());
                            $(document.getElementById("iframe-workItem").contentDocument.body.getElementsByTagName('img')).css("width", "100%");
						});
						iframe.attr('src', json.results.url);	*/
						  if(typeof clientType!=="undefined"){         
							  if(clientType==1){  //ios
								  document.addEventListener("deviceready", function(){
									TrunPage.openWebView(json.results.url,'html','正文');
								  }, false);
							  }else{
								  	//android
								  	TrunPage.openWebView(json.results.url,'html','正文');
							  }
						  }							  
			  
                    } else {
                        empty.show();
                    }
                }
            });
        }
});  
    
    $$(page.container).find('.tab3').on('show', function () {
        $$(page.navbarInnerContainer).find('.center').text('附件');
        var tab = $$(this),
            ul = tab.find('.list-block ul'),
            empty = tab.find('.empty-view');
        if (workData) {
        	if(workData.hiddenValue.formDefId=="mangoMeetingApply"){
        		 $$.getJSONP(SERVER_PATH + 'customattachmentlist.do', {
                     businessId: workData.hiddenValue.businessId
                 }, function (json) {
                     if (json.code == 1) {
                         ul.children().remove();
                         $$.each(json.results, function (index, value) {
                             value.suffix = value.ext || 'file';

                             var html = Template7.templates.fileTemplate(value);
                             ul.append(html);
                         });
                         empty[ul.children().length > 0 ? 'hide' : 'show']();
                     }
                 });
        	}else{
        		$$.getJSONP(SERVER_PATH + 'attachmentlist.do', {
                	formDefId: workData.hiddenValue.formDefId,
                    businessId: workData.hiddenValue.businessId
                }, function (json) {
                    if (json.code == 1) {
                        ul.children().remove();
                        $$.each(json.results, function (index, value) {
                            value.suffix = value.ext || 'file';

                            var html = Template7.templates.fileTemplate(value);
                            ul.append(html);
                        });
                        empty[ul.children().length > 0 ? 'hide' : 'show']();
                    }
                });
        	}
        }
    });
    var confirmList, index = 0;
    $$(page.container).find('.tab4').on('show', function () {
        $$(page.navbarInnerContainer).find('.center').text('流程');
        var tab = $$(this),
            ul = tab.find('.list-block ul');

        if (workData && !confirmList) {
            confirmList = workData.confirmList;

            ul.append('<li class="list-group-title">详细申请流程</li>');
            var lastOne = $$('<li class="item-content item-timedot item-timedot-last">' +
                '<div class="item-media"><span></span></div>' +
                '<div class="item-inner">' +
                '<div class="item-subtitle">查看更多</div>' +
                '</div>' +
                '</li>');

            $$.each(confirmList, function (index, value) {
                value.index = confirmList.length - index;
            });
            function loadPage() {
                lastOne.remove();
                for (var i = 0; i < 4 && index < confirmList.length; i++) {
                    var html = Template7.templates.applyConfirmTemplate(confirmList[index++]);
                    ul.append(html);
                }
                if (index < confirmList.length) {
                    ul.append(lastOne);
                }
            }
            lastOne.click(loadPage).click();
        }
    });

    var tab1 = $$(page.container).find('.tab1'),
        form = tab1.find('form'),
        list = tab1.find('.tab1 .list-block ul');
    $$.getJSONP(SERVER_PATH + 'getWorkItemInfo.do', {pkId: params.id}, function (json) {

        if (json.code == 1) {
            workData = json.results;

            list.append('<li class="list-group-title">' + workData.formtitle + '</li>');

            $$.each(workData.hiddenValue, function (key, value) {
                var li = $$('<li><div class="item-content" style="display: none"><div class="item-inner">' +
                    '<div class="item-title label"></div>' +
                    '<div class="item-input">' +
                    '<input type="text">' +
                    '</div>' +
                    '</div></div></li>');
                li.find('input').attr('name', key);
                li.find('input').val(value);
                list.append(li);
            });

            buildComponents(list, workData.component,workData.fenfaCard);

            // 审批意见
            if (workData.showConfirm && (params.wt == 0 || (params.wt == 1 && !workData.isEnd))) {
                var key = params.wt == 0 ? 'confirminfo' : 'comment';
                var li = $$('<li class="align-top">' +
                    '<div class="item-content">' +
                    '<div class="item-inner">' +
                    '<div class="item-title label">请签署您的意见</div>' +
                    '<div class="item-input input-dropdown">' +
                    '<textarea name="' + key + '" class="resizable"></textarea><a class="dropdown-toggle" href="#"><i class="icon"></i></a>' +
                    '<ul></ul>' +
                    '</div>' +
                    '</div>' +
                    '</div><div id="showConfirmImg"></div>' +
                    '</li>');
                $$.each(workData.commonAdvice, function (index, keyword) {
                    li.find('ul').append('<li><a class="dropdown-option" href="#">' +
                        '<i>●&nbsp;&nbsp;</i><span>' + keyword.CONTENT + '</span></a></li>');
                });
                list.append(li);
            }

            if (workData.processTask) {

                var li = $$('<li><div class="item-content" style="display: none"><div class="item-inner">' +
                    '<div class="item-title label"></div>' +
                    '<div class="item-input">' +
                    '<input type="text" name="taskid">' +
                    '</div>' +
                    '</div></div></li>');
                li.find('input').val(workData.processTask.taskid);
                list.append(li);

                if (params.wt == 0) {
                    if (workData.processTask.isend) {
                        li = $$('<li><div class="item-content"><div class="item-inner item-inner-long">' +
                                '<div class="item-title label">选择下一步办理步骤</div>' +
                                '<div class="item-input radio-group"></div>' +
                                '</div></div></li>');
                        li.find('.item-input').append('<label class="label-radio">'
                            + '<input type="radio" name="submitTo" value="' + workData.processTask.transitionlist[0].lineName + '" checked="checked">'
                            + '<div class="form-checkbox">办结</div>'
                            + '</label>');
                        list.append(li);
                    } else {
                        // 下一步部门
                        li = $$('<li><div class="item-content"><div class="item-inner item-inner-long">' +
                            '<div class="item-title label">选择当前部门</div>' +
                            '<div class="item-input radio-group"></div>' +
                            '</div></div></li>');
                        $$.each(workData.processTask.depart, function (index, value) {
                            li.find('.item-input').append('<label class="label-radio">'
                                + '<input type="radio" name="departId" value="' + value.departId + (index === 0 ? '" checked="checked">' : '">')
                                + '<div class="form-checkbox">' + value.departName + '</div>'
                                + '</label>');
                        });
                        list.append(li);

                        // 下一步办理步骤
                        li = $$('<li><div class="item-content"><div class="item-inner item-inner-long">' +
                            '<div class="item-title label">选择下一步办理步骤</div>' +
                            '<div class="item-input radio-group"></div>' +
                            '</div></div></li>');
                        $$.each(workData.processTask.transitionlist, function (index, value) {
                            var lineName = value.lineType === 'end' ? '办结' : value.lineName;
                            li.find('.item-input').append('<label class="label-radio">'
                                + '<input type="radio" name="submitTo" value="' + value.lineName + (index === 0 ? '" checked="checked">' : '">')
                                + '<div class="form-checkbox">' + lineName + '</div>'
                                + '</label>');
                        });
                        list.append(li);

                        // 下一步处理人
                        list.append('<li><div class="item-content"><div class="item-inner item-inner-long">' +
                            '<div class="item-title label">选择下一步处理人</div>' +
                            '<div class="item-input task-handle-user"></div>' +
                            '</div></div></li>');
                    }
                }
            }

            // checkbox
            if (params.wt == 0) {
                list.append('<li class="item-content" style="min-height: 0"><label class="label-checkbox">' +
                    '<input type="checkbox" name="isPushMessage" value="true" checked="checked">' +
                    '<div class="item-media"><i class="icon icon-form-checkbox"></i></div>' +
                    '<div class="item-inner">' +
                    '<div class="item-title">给处理人推送消息提醒</div>' +
                    '</div>' +
                    '</label></li>');
            }

            // bottom buttons
            if (params.wt == 0) {
                var li = $$('<li><div class="item-content"><div class="item-inner row button-row"></div></div></li>'),
                    count = 1;
                li.find('.item-inner').append('<a href="#" data-cmMenuCode="submit" class="button active">确定</a>');
                $$.each(json.results.confirmMap.confirmMenuList, function (index, value) {
                    if (value.cmMenuCode == 'fenfa') {
                        li.find('.item-inner').append('<div class="button-pad"></div>');
                        li.find('.item-inner').append('<a href="#" data-cmMenuCode="' + value.cmMenuCode + '" class="button active">分发</a>');
                        count++;
                    } else if (value.cmMenuCode == 'relayId') {
                        li.find('.item-inner').append('<div class="button-pad"></div>');
                        li.find('.item-inner').append('<a href="#" data-cmMenuCode="' + value.cmMenuCode + '" class="button active">传阅</a>');
                        count++;
                    } else if (value.cmMenuCode == 'signComment') {
                        li.find('.item-inner').append('<div class="button-pad"></div>');
                        li.find('.item-inner').append('<a href="#" data-cmMenuCode="' + value.cmMenuCode + '" class="button active">手写签批</a>');
                        count++;
                    } else if (value.cmMenuCode == 'delete') {
                        li.find('.item-inner').append('<div class="button-pad"></div>');
                        li.find('.item-inner').append('<a href="#" data-cmMenuCode="' + value.cmMenuCode + '" class="button active">流程删除</a>');
                        count++;
                    }
                });
                li.find('.item-inner').children('.button.active').addClass('col-' + parseInt(100 / count));
                list.append(li);
            } else {
                var li = $$('<li><div class="item-content"><div class="item-inner row button-row"></div></div></li>');
                li.find('.item-inner').append('<a href="#" data-cmMenuCode="doDistribution" class="button active col-100">确定</a>');
                list.append(li);
            }

            var handleUserInput = list.find('.task-handle-user');
            if (handleUserInput.length > 0) {
                buildHandleUserInput(handleUserInput, json.results.processTask, 'selecTHandleUseIdHid');
                // change triggered on the checked element
                list.find('input[name="submitTo"], input[name="departId"]').change(function () {
                    var trasactionLine = list.find('input[name="submitTo"]:checked').val(),
                        departId = list.find('input[name="departId"]:checked').val();
                    //console.log('select ' + trasactionLine + ' & ' + departId);
                    $$.getJSONP(SERVER_PATH + 'getHandleByNextNode.do', {
                        workItemId: workData.hiddenValue.workitemid,
                        trasactionLine: trasactionLine,
                        departId: departId
                    }, function (json) {
                        if (json.code == 1) {
                            buildHandleUserInput(handleUserInput, json.results, 'selecTHandleUseIdHid');
                        }
                    });
                });
            }

            list.find('textarea.resizable').each(function () {
                myApp.resizableTextarea(this);
            }).change();
        }
    });

    list.on('click', '.button.active', function () {
        var menuCode = $$(this).attr('data-cmMenuCode');
        if (menuCode === 'submit') {
            var data = myApp.formToJSON(form);
			data['.fcid'] = workData['.fcid'];
            $$.each(data, function (key, value) {
                if ($$.isArray(value)) {
                    data[key] = value.join(',');
                }
            });
            data.isPushMessage = !!data.isPushMessage;

            // validate
            if (workData.component) {
                for (var i = 0; i < workData.component.length; i++) {
                   var comp = workData.component[i];
                    if (comp.required && comp.type === 'edit' && !data[comp.columnName]) {
                        myApp.toast(comp.displayName + '未填写', '<div>×</div>', {}).show(true);
                        return;
                    }

                    if (comp.componentName == 'Timestamp' || comp.componentName == 'CurrentDate') {
                        if (comp.onlyDate != 'true') {
                            data[comp.columnName] = data[comp.columnName].replace('T', ' ');
                        }
                    }
                }
            }

            //选中end_后应该不要选择处理人了
            var needCheckNextProcessor = true;
            $$.each(workData.processTask.transitionlist, function (index, value) {
                if (value.lineType === 'end') {
                    needCheckNextProcessor = false;
                    return false;
                }
            });
            if (needCheckNextProcessor && list.find('.task-handle-user').length > 0 && !data.selecTHandleUseIdHid) {
                myApp.toast('请选择处理人', '<div>×</div>', {}).show(true);
                return;
            }

            data.confirmImg = confirmImg;
            
            myApp.showIndicator();
            $$.getJSONP(SERVER_PATH + 'workitemAction.do', data, function (json) {
                myApp.hideIndicator();
                if (json.code == 1) {
                    myApp.toast('成功', '<div>√</div>', {}).show(true);
                    page.view.back();
                    $$('.page[data-page="work-item-list"] .pull-to-refresh-content').trigger('refresh');
                } else {
                    myApp.toast(json.msg, '<div>×</div>', {}).show(true);
                }
            });
        } else if (menuCode === 'fenfa' || menuCode === 'relayId') {
            var params = {
                action: menuCode,
                actionName: $$(this).text(),
                workitemid: workData.hiddenValue.workitemid,
                title: workData.hiddenValue.docTitle,
                fileReleaseContent: workData.hiddenValue.formDefId + '_' + workData.hiddenValue.businessId
            };
            page.view.router.load({url: 'fenfa.html?' + $$.serializeObject(params)});
        } else if (menuCode === 'doDistribution') {
            var comment = list.find('textarea[name="comment"]').val();

            myApp.showIndicator();
            $$.getJSONP(SERVER_PATH + 'doDistribution.do', {distributionId: workData.docRelayId, comment: comment}, function (json) {
                myApp.hideIndicator();
                if (json.code == 1) {
                    myApp.toast('成功', '<div>√</div>', {}).show(true);
                    page.view.back();
                    $$('.page[data-page="work-item-list"] .pull-to-refresh-content').trigger('refresh');
                } else {
                    myApp.toast(json.msg, '<div>×</div>', {}).show(true);
                }
            });
        } else if (menuCode === 'signComment') {
			TrunPage.signDoc(signDocCallback);
		} else if (menuCode === 'delete') {
			myApp.confirm("确定删除？", "提示", function () {
				var params = {
					formControllerId:workData.formControllerId,
					isAdmin:true,
					formDefId:workData.hiddenValue.formDefId,
					pid:workData.hiddenValue.id
				};
				myApp.showIndicator();
		        $$.getJSONP(SERVER_PATH + 'deleteFormDataAtStartProcess.do', params, function (json) {
		            myApp.hideIndicator();
		            if (json.code == 1) {
		                myApp.toast('删除成功', '<div>√</div>', {}).show(true);
		                page.view.back({force: true, url: document.location.href});
		            } else {
		                myApp.toast(json.msg, '<div>×</div>', {}).show(true);
		            }
		        });
            });
		}
    });
});


myApp.onPageInit('fenfa-relayId', function (page) {
    console.log("onPageInit " + page.name);
    var params = page.query,
        form = $$(page.container).find('form');

    $$(page.container).find('textarea[name="docTitle"]').val(decodeURIComponent(params.title));
    $$(page.container).find('textarea[name="docRemark"]').
        parents('.item-content').find('.item-title.label').text(params.action === 'fenfa' ? '分发说明' : '传阅说明');

    var handleUserInput = $$(page.container).find('.task-handle-user');
    buildHandleUserInput(handleUserInput, {
        selectUserMode: "selectUser",
        taskHandleListJsonList: []
    }, 'mainSendUserIds');

    var button = $$(page.container).find('.button.active');
    button.text(decodeURIComponent(params.actionName))
    button.click(function () {
        var data = myApp.formToJSON(form);
        $$.each(data, function (key, value) {
            if ($$.isArray(value)) {
                data[key] = value.join(',');
            }
        });
        data.workitemid = params.workitemid;
        data.fileReleaseContent = params.fileReleaseContent;

        // validate
        if (!data.mainSendUserIds) {
            myApp.toast('请选择处理人', '<div>×</div>', {}).show(true);
            return;
        }

        myApp.showIndicator();
        var url = params.action === 'fenfa' ? 'distribute.do' : 'docRelay.do';
        $$.getJSONP(SERVER_PATH + url, data, function (json) {
            myApp.hideIndicator();
            if (json.code == 1) {
                myApp.toast('成功', '<div>√</div>', {}).show(true);
                page.view.back();
            } else {
                myApp.toast(json.msg, '<div>×</div>', {}).show(true);
            }
        });
    });

});


myApp.onPageInit('quick-start', function (page) {
    console.log("onPageInit " + page.name);
    var params = page.query,
        workData,
        form = $$(page.container).find('form'),
        list = $$(page.container).find('.list-block ul');

    $$.getJSONP(SERVER_PATH + 'quickStart.do', {formId: params.formId}, function (json) {
        if (json.code == 1) {
            workData = json.results;

            list.append('<li class="list-group-title">' + workData.formtitle + '</li>');

            buildComponents(list, workData.component,null);

            // 当前部门
            if (workData.process.currentDeparts){
                var li = $$('<li><div class="item-content"><div class="item-inner item-inner-long">' +
                        '<div class="item-title label">当前部门</div>' +
                        '<div class="item-input radio-group"></div>' +
                        '</div></div></li>'),
                    radioGroup = li.find('.item-input');
                $$.each(workData.process.currentDeparts, function (index, value) {
                    radioGroup.append('<label class="label-radio">'
                        + '<input type="radio" name="departId" value="' + value.departId + (index === 0 ? '" checked="checked">' : '">')
                        + '<div class="form-checkbox">' + value.departName + '</div>'
                        + '</label>');
                });
                list.append(li);
            }

            // 下一步办理步骤
            {
                var li = $$('<li><div class="item-content"><div class="item-inner item-inner-long">' +
                        '<div class="item-title label">选择下一步办理步骤</div>' +
                        '<div class="item-input radio-group"></div>' +
                        '</div></div></li>'),
                    radioGroup = li.find('.item-input');
                $$.each(workData.process.nextNodeList, function (index, value) {
                    radioGroup.append('<label class="label-radio">'
                        + '<input type="radio" name="outcome" value="' + value.nodeLineName + (index === 0 ? '" checked="checked">' : '">')
                        + '<div class="form-checkbox">' + value.nodeLineName + '</div>'
                        + '</label>');
                });
                list.append(li);
            }

            // 下一步处理人
            list.append('<li><div class="item-content"><div class="item-inner item-inner-long">' +
                '<div class="item-title label">选择下一步处理人</div>' +
                '<div class="item-input task-handle-user"></div>' +
                '</div></div></li>');

            // bottom buttons
            list.append('<li><div class="item-content"><div class="item-inner row button-row"><a href="#" data-cmMenuCode="submit" class="button active col-100">确定</a></div></div></li>');

            var handleUserInput = list.find('.task-handle-user');
            buildHandleUserInput2(handleUserInput, workData.process, 'selecTHandleUseIdHid');
            // change triggered on the checked element
            list.find('input[name="outcome"],input[name="departId"]').change(function() {
                var nodeLineName = list.find('input[name="outcome"]:checked').val(),                
                	departId = list.find('input[name="departId"]:checked').val();
                $$.getJSONP(SERVER_PATH + 'getNextFromStart.do', {
                    formDefId: workData.formid,
                    workflowdefinitionpdid: workData.workflowdefinitionpdid,
                    nodeLineName: nodeLineName,
                    departId: departId
                }, function (json) {
                    if (json.code == 1) {
                        buildHandleUserInput2(handleUserInput, json.results, 'selecTHandleUseIdHid');
                    }
                });
            });

            list.find('textarea.resizable').each(function () {
                myApp.resizableTextarea(this);
            }).change();
        }
    });

    list.on('click', '.button.active', function () {
        if (!workData) {
            return;
        }

        var data = myApp.formToJSON(form);
        data.process = true;
        data.workflowdefinitionpdid = workData.workflowdefinitionpdid;
        data['.fcid'] = workData['.fcid'];
        $$.each(data, function (key, value) {
            if ($$.isArray(value)) {
                data[key] = value.join(',');
            }
        });

        // validate
        for (var i = 0; i < workData.component.length; i++) {
            var comp = workData.component[i];
            if (comp.required && comp.type === 'edit' && !data[comp.columnName]) {
                myApp.toast(comp.displayName + '未填写', '<div>×</div>', {}).show(true);
                return;
            }

            if (comp.componentName == 'Timestamp' || comp.componentName == 'CurrentDate') {
                if (comp.onlyDate != 'true') {
                    data[comp.columnName] = data[comp.columnName].replace('T', ' ');
                }
            }
        }
        if (!data.selecTHandleUseIdHid) {
            myApp.toast('请选择处理人', '<div>×</div>', {}).show(true);
            return;
        }

        myApp.showIndicator();
        $$.getJSONP(SERVER_PATH + workData.formAction, data, function (json) {
            myApp.hideIndicator();
            if (json.code == 1) {
                myApp.toast('成功', '<div>√</div>', {}).show(true);
                page.view.back();
            } else {
                myApp.toast(json.msg, '<div>×</div>', {}).show(true);
            }
        });
    });
});

function signDocCallback(data) {
	var imageUrl = data;
	convertImgToBase64(imageUrl, function(base64Img) {
		var noTypeBase64Img = base64Img.split(',')[1];
		confirmImg = noTypeBase64Img;
	});
	$$("#showConfirmImg").html("<p><img width='100%' height='' src='"+ imageUrl +"'></p>");//拿到签批的图片回显在处理单上
}